<template>
  <div>
    <Breadcrumb></Breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <!-- 用户搜索添加 -->
      <el-row :gutter="20">
        <el-col :span="12">
          <el-input
            placeholder="请输入内容"
            class="input-with-select"
            v-model="paramUser.query"
            clearable
            @blur="getTableData"
          >
            <el-button slot="append" icon="el-icon-search" @click="getTableData"></el-button>
          </el-input>
        </el-col>
        <el-col :span="8">
          <el-button type="primary" @click="dialogVisible=true">添加用户</el-button>
        </el-col>
      </el-row>
      <!-- table表格区域 -->
      <el-table :data="tableData.users" border style="width: 100%">
        <el-table-column type="index" label="#" width="80"></el-table-column>
        <el-table-column prop="username" label="姓名" width="180"></el-table-column>
        <el-table-column prop="email" label="邮箱"></el-table-column>
        <el-table-column prop="mobile" label="电话"></el-table-column>
        <el-table-column prop="role_name" label="角色"></el-table-column>
        <el-table-column prop="mg_state" label="状态">
          <template v-slot="scope">
            <el-switch v-model="scope.row.mg_state" @change="savestate(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" fixed="right" width="200">
          <template v-slot="scope">
            <el-button type="primary" icon="el-icon-edit" circle @click="enditData(scope.row)"></el-button>
            <el-button type="danger" icon="el-icon-delete" circle @click="del(scope.row.id)"></el-button>
            <el-button type="warning" icon="el-icon-star-off" circle @click="setRole(scope.row)"></el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="tableData.total"
        :page-size="paramUser.pagesize"
        :current-page="paramUser.pagenum"
        @current-change="getNowpage"
      ></el-pagination>
    </el-card>

    <!-- //添加数据 -->
    <el-dialog title="收货地址" :visible.sync="dialogVisible">
      <el-form :model="addDataobj" :rules="addRules" ref="addfrom">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input autocomplete="off" v-model="addDataobj.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" label-width="120px" prop="password">
          <el-input autocomplete="off" v-model="addDataobj.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input autocomplete="off" v-model="addDataobj.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="120px" prop="mobile">
          <el-input autocomplete="off" v-model="addDataobj.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="getAddDataobj">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="setRoleDialogVisible" width="50%">
      <div>
        <p>当前的用户:{{userInfo.username}}</p>
        <p>当前的角色:{{userInfo.role_name}}</p>
        <p>
          分配新角色:
          <el-select v-model="selectedRoleId" placeholder="请选择角色">
            <!-- :label 显示文本，:value 选中值 -->
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            ></el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRoleDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="colesRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑数据对话框 -->
    <el-dialog title="编辑数据" :visible.sync="enditVisible">
      <el-form :model="enditshuju" :rules="enditrules" ref="enditref">
        <el-form-item label="用户名" label-width="120px" prop="username">
          <el-input autocomplete="off" v-model="enditshuju.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" label-width="120px" prop="email">
          <el-input autocomplete="off" v-model="enditshuju.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" label-width="120px" prop="mobile">
          <el-input autocomplete="off" v-model="enditshuju.mobile"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="enditVisible = false">取 消</el-button>
        <el-button type="primary" @click="getEndit(enditshuju.id)">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getUserData,
  getAddData,
  getSaveState,
  getSetRole,
  getColesRole,
  getPutEndit,
  getRemove
} from "@/api/User/user.js";
import Breadcrumb from "@/components/Breadcrumb";
export default {
  components: { Breadcrumb },
  data() {
    //邮箱验证格式
    var checkEmail = (rule, value, callback) => {
      var reg = /^[A-Za-z0-9]+([_\.][A-Za-z0-9]+)*@([A-Za-z0-9\-]+\.)+[A-Za-z]{2,6}$/;
      if (!reg.test(value)) {
        return callback(new Error("请输入正确的邮箱格式"));
      } else {
        callback();
      }
    };
    return {
      tableData: [], //用户列表数据
      title: "", //input输入框内容,
      paramUser: {
        query: "",
        pagenum: 1,
        pagesize: 3
      }, //用户列表参数配置
      dialogVisible: false, //添加用户开关
      addDataobj: [], //添加用户需要提交的数据
      //添加数据对象
      addDataobj: {
        username: "",
        password: "",
        email: "",
        mobile: ""
      },
      //添加对话框的验证规则
      addRules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        password: [
          { required: true, message: "请输入正确的密码", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ],
        email: [
          { required: true, message: "请输入你的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入正确的手机号", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ]
      },
      setRoleDialogVisible: false, //分配角色对话框开关
      userInfo: {}, //权限管理当前用户信息
      selectedRoleId: "", //新的角色id
      rolesList: [], //角色列表
      // 添加编辑对话框的验证规则
      enditrules: {
        email: [
          { required: true, message: "请输入你的邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" }
        ],
        mobile: [
          { required: true, message: "请输入正确的手机号", trigger: "blur" },
          { min: 3, max: 8, message: "长度在 3 到 8 个字符", trigger: "blur" }
        ]
      },
      // 编辑数据
      enditshuju: {},
      enditVisible: false
    };
  },
  methods: {
    async getTableData() {
      let { data: res } = await getUserData(this.paramUser);
      if (res.meta.msg != "获取管理员列表成功") {
        this.$message.error("获取管理员列表失败");
      }
      this.$message.success("获取管理员列表成功");
      this.tableData = res.data; //用户列表数据
      console.log(res.data);
    },
    //触发分页器
    getNowpage(nowpage) {
      console.log(nowpage);
      this.paramUser.pagenum = nowpage;
      this.getTableData();
    },
    //添加用户提交
    getAddDataobj() {
      this.$refs.addfrom.validate(async vaild => {
        console.log(vaild);
        if (vaild) {
          //   提交接口的数据;
          var data = await getAddData(this.addDataobj);
          console.log(data);
          if (data.meta.status == 201) {
            this.$message.success("用户添加成功");
            this.dialogVisible = false;
            this.getTableData();
          } else {
            this.$message.error("用户添加失败");
          }
        }
      });
    },
    async savestate(a) {
      console.log(a);
      let res = await getSaveState(a.id, a.mg_state);
      console.log(res);
      if (res.data.meta.status == 200) {
        this.$message({
          message: "状态设置成功",
          type: "success"
        });
      }
    },
    // /.点击分配权限打开对话框并请求分配角色信息
    async setRole(value) {
      const res = await getSetRole(value);
      this.rolesList = res.data.data;
      console.log(this.rolesList);
      this.setRoleDialogVisible = true;
      this.userInfo = value;
    },
    // 提交分配角色请求
    async colesRole() {
      let res = await getColesRole(this.userInfo.id, {
        rid: this.selectedRoleId
      });
      console.log(res);
      if (res.meta.msg != "设置角色成功") {
        this.$message.error("分配角色失败");
      }
      this.$message.success("分配角色成功");
      this.setRoleDialogVisible = false;
      this.getTableData();
    },

    // 编辑用户框打开
    enditData(valuea) {
      console.log(valuea);
      this.enditVisible = true; //编辑框的显示
      this.enditshuju = valuea;
    },
    // 编辑提交用户数据
    getEndit(id) {
      //当数据效验成功后调用接口
      this.$refs.enditref.validate(async value => {
        if (value) {
          var obj = {
            email: this.enditshuju.email,
            mobile: this.enditshuju.mobile
          };
          const res = await getPutEndit(id, obj);
          console.log(res);
          if (res.meta.msg != "更新成功") {
            this.$message.error("更新失败");
          }
          this.$message.success("更新成功");
          this.enditVisible = false;
          this.getTableData();
        }
      });
    },
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          const { data: res } = await getRemove(id);
          console.log(res);
          if (res.meta.status == 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
          }
          this.getTableData();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    }
  },
  mounted() {
    this.getTableData();
  }
};
</script>

<style lang="scss" scoped>
.el-card {
  margin-top: 20px;
}
.el-table {
  margin-top: 20px;
}
</style>